package org.example.mrrope.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.mrrope.service.UpdatePurchasingPriceService;
import org.example.mrrope.utils.DingUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Lizzy
 * @date 2024/07/25
 * @desc 更新采购价
 */

@Service
@Slf4j
public class UpdatePurchasingPriceServiceImpl implements UpdatePurchasingPriceService {

    @Autowired
    DingUtil dingUtil;

    String NAME_ID;
    String PRICE_ID;
    String TABLE_ID;
    String SO_ID;
    String PURCHASE_PRICE_ID = "numberField_lv6campa";
    String PURCHASE_NAME_ID = "textField_lup0qelz";
    String PURCHASE_TABLE_ID = "tableField_lup0qelv";
    String PURCHASE_SO_ID = "textField_lv5fbxke";
    String FROM_UUID;

    @Override
    @Async
    public Integer updateCottonYarnPurchasingPrice(String id, String type) {
        //找到SO号下所有表
        NAME_ID = "textField_lxwy8xnq";
        PRICE_ID = "numberField_lyz9hg1z";
        TABLE_ID = "tableField_lwg8vm75";
        SO_ID = "textField_lyz4wuwl";
        FROM_UUID = "FORM-0874A95C33B240AF94AEE5E888DC7CE0G3BF";




        return getWorkOrderIds(id, FROM_UUID, type);
    }

    @Override
    @Async
    public Integer updateAccessoriesPurchasingPrice(String id, String type) {
        //找到SO号下所有表
        int reNumber;
        NAME_ID = "textField_lujgt59f";
        PRICE_ID = "numberField_lz11o70s";
        TABLE_ID = "tableField_lvxe56yi";
        SO_ID = "textField_lyz6ump9";
        FROM_UUID = "FORM-A6E69C4290D3475C8F31A1DF76A03201NPH8";
        reNumber = getWorkOrderIds(id, FROM_UUID, type);//制结
        if (reNumber != 0) {
            log.error("更新制结配件子表采购价格失败");
        }
        FROM_UUID = "FORM-BF820F87D69048E3AC38F5FD58F6DDDDRHX4";
        reNumber = getWorkOrderIds(id, FROM_UUID, type);//缝纫
        if (reNumber != 0) {
            log.error("更新缝纫配件子表采购价格失败");
        }
        return reNumber;
    }

    @Override
    @Async
    public Integer updatePackingMaterialPurchasingPrice(String id, String type) {
        //找到SO号下所有表
        NAME_ID = "textField_lxwy8xnq";
        PRICE_ID = "numberField_lyz9hg1z";
        TABLE_ID = "tableField_lwg8vm75";
        SO_ID = "textField_lyz4wuwl";
        FROM_UUID = "FORM-0874A95C33B240AF94AEE5E888DC7CE0G3BF";
        return getWorkOrderIds(id, FROM_UUID, type);
    }

    private Integer getWorkOrderIds(String id, String fromUuid, String type) {
        try {
            JSONObject originJsonObject = new JSONObject(dingUtil.getYidaById(id));
            log.info("getYidaById方法查询采购订单返回值-----》" + originJsonObject);
            JSONArray purchaseTable = originJsonObject.getJSONArray(PURCHASE_TABLE_ID);
            log.info("采购订单子表-----》" + purchaseTable);
            JSONObject searchJson = new JSONObject();
            searchJson.put(SO_ID, originJsonObject.has(PURCHASE_SO_ID) ? originJsonObject.getString(PURCHASE_SO_ID) : "");
            log.info("搜索type:{}派工单的搜索条件----->{} ", type, searchJson);
            List<String> idList = dingUtil.getYiDaIds(fromUuid, searchJson.toString());
            log.info("getYiDaIds方法搜索 {} 派工单返回值-----》 {} ", type, idList);
            if (idList.isEmpty()) {
                return 1;
            }
            return updatePrices(purchaseTable, idList, TABLE_ID, NAME_ID, PRICE_ID);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Integer updatePrices(JSONArray purchaseTable, List<String> idList, String tableId, String nameId, String priceId) throws Exception {
        Map<String, Double> priceMap = createPriceMap(purchaseTable, PURCHASE_NAME_ID, PURCHASE_PRICE_ID);
        int reNumber = 1;
        for (String orderId : idList) {
            log.info("派工单id-----》" + orderId);
            JSONObject orderJsonObject = new JSONObject(dingUtil.getYidaById(orderId));
            log.info("派工单-----》" + orderJsonObject);
            JSONArray orderPurchaseTable = orderJsonObject.getJSONArray(tableId);
            log.info("派工单子表-----》" + orderPurchaseTable);
            String res = updateTable(orderPurchaseTable, priceMap, nameId, priceId, tableId, orderId);
            log.info("派工单更新结果-----》" + res);
            if (res != null) {
                reNumber = 0;
            } else {
                reNumber = 1;
            }
        }
        return reNumber;
    }

    private Map<String, Double> createPriceMap(JSONArray table, String purchaseNameId, String purchasePriceId) throws JSONException {
        Map<String, Double> map = new HashMap<>();
        for (int i = 0; i < table.length(); i++) {
            JSONObject item = table.getJSONObject(i);
            if (item.has(purchaseNameId)) {
                map.put(item.getString(purchaseNameId), item.getDouble(purchasePriceId));
            }
        }
        log.info("创建的map-----》" + map);
        return map;
    }

    private String updateTable(JSONArray table, Map<String, Double> priceMap, String nameId, String priceId, String tableId, String instanceId) throws JSONException {
        JSONObject upJson = new JSONObject();
        JSONArray newTable = new JSONArray();
        for (int i = 0; i < table.length(); i++) {
            JSONObject item = table.getJSONObject(i);
            if (item.has(nameId) && priceMap.containsKey(item.getString(nameId))) {
                item.put(priceId, priceMap.get(item.getString(nameId)));
            }
            newTable.put(item);
        }
        log.info("更新的子表值-----》" + newTable);
        upJson.put(tableId, newTable);
        log.info("传入的更新参数id:{},upJson{} -----》", instanceId, upJson);
        try {
            String res = dingUtil.UpdateYiDa(instanceId, upJson);
            log.info("更新后的返回值-----》" + res);
            return res;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
